package com.junlinpro.service;


import java.util.Date;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.junlinpro.entity.MessageEntity;
import com.junlinpro.entity.RegisterEntity;
import com.junlinpro.utils.ByteUtil;
import com.junlinpro.utils.Constant;
import com.junlinpro.utils.CrcUtils;
import com.junlinpro.utils.DateUtil;
import com.junlinpro.utils.MessageUtil;
import com.junlinpro.utils.SocketChannelMap;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CollectorSetterService {

    @Async
    public void modifyTimeInterval(Channel ctx,int cardId, byte channelId, long timeInterval) {
    	byte cmd = 0x0E;
    	
    	//不能超过4字节
    	int timeIntervalData = (int)timeInterval;
    	byte[] byteData = ByteUtil.intToByteArray(timeIntervalData);

        MessageEntity sendMsg = new MessageEntity();
        sendMsg.setCardId(cardId);
        sendMsg.setChannelId(channelId);
        
        sendMsg.setCmd(cmd);
        sendMsg.setData(byteData);
        //23加数据4个字节
        sendMsg.setAllLen(27);
        sendMsg.setVersionNum(Constant.HARDWARE_VERSION);       

        // 帧序号
        sendMsg.setFrameId(0);
        
        // 类型 0x01
        byte cardType = 0x00;      
        sendMsg.setCardType(cardType);

        // 转换成时间戳
        int utcTimeStamp = DateUtil.transForMilliSecond(new Date());
        sendMsg.setOccurTime(utcTimeStamp);

        // 对下发信息封装
        byte[] byteMsg = MessageUtil.rtnMessageTobyte(sendMsg);

        log.info("下发报文：修改定时上报时间间隔：" + ByteUtil.bytesToHexString(byteMsg));

        log.info("下发的channel：" + ctx.toString());

        try {
            // 下发信息
            ctx.writeAndFlush(Unpooled.copiedBuffer(byteMsg));

        } catch (Exception e) {
            log.error("下发报文：修改定时上报时间间隔："+e.getMessage());
        }
    }
    
    @Async
    public void modifyAlarmArgs(Channel ctx, int cardId, byte channelId, byte oneValue, byte twoValue, int thresholdValue) {
    	byte cmd = 0x13;
        
        MessageEntity sendMsg = new MessageEntity();
        sendMsg.setCardId(cardId);
        sendMsg.setChannelId(channelId);        
        sendMsg.setCmd(cmd);
        
        byte[] byteData = new byte[4];
        byteData[0] = Byte.valueOf(String.valueOf(oneValue));
        byteData[1] = Byte.valueOf(String.valueOf(twoValue));
        byte[] byteThreshold = ByteUtil.intTo2ByteArray(thresholdValue);
        byteData[2] = byteThreshold[0];
        byteData[3] = byteThreshold[1];
        //23加数据4个字节
        sendMsg.setData(byteData);        
        sendMsg.setAllLen(27);
        sendMsg.setVersionNum(Constant.HARDWARE_VERSION);

        // 帧序号
        sendMsg.setFrameId(0);
        // 类型
        byte cardType = 0x00;
        sendMsg.setCardType(cardType);

        // 转换成时间戳
        int utcTimeStamp = DateUtil.transForMilliSecond(new Date());
        sendMsg.setOccurTime(utcTimeStamp);

        // 对回复信息封装
        byte[] byteMsg = MessageUtil.rtnMessageTobyte(sendMsg);

        log.info("下发报文：修改报警参数：" + ByteUtil.bytesToHexString(byteMsg));

        log.info("下发的channel：" + ctx.toString());

        try {
            // 回复信息
            ctx.writeAndFlush(Unpooled.copiedBuffer(byteMsg));

        } catch (Exception e) {
        	log.error("下发报文：修改报警参数失败："+e.getMessage());
        }
    }

    @Async
    public void modifyDigitalPotentiometer(Channel channel, int cardId, byte channelId, int dpValue ) {
    	byte cmd = 0x15;
    	// 任务id
        String taskKey = SocketChannelMap.dpTaskKey + cardId;
        
        MessageEntity msg = new MessageEntity();
        msg.setCardId(cardId);
        msg.setChannelId(channelId);       
        
        //数据为 2 字节 高字节在前? 
        byte[] byteData = ByteUtil.intTo2ByteArray(dpValue);
        msg.setData(byteData);
        msg.setCmd(cmd);
        //23加数据2个字节
        msg.setAllLen(25);
        msg.setVersionNum(Constant.HARDWARE_VERSION);        
               
        int utcTimeStamp = DateUtil.transForMilliSecond(new Date());
        msg.setOccurTime(utcTimeStamp);

        byte[] byteMsg = MessageUtil.rtnMessageTobyte(msg);

        try {
            // 预防嵌入式收不到 每隔2秒下发一次 持续下发1分钟的命令
            for (int i = 0; i < 30; i++) {
                if (SocketChannelMap.taskMapGet(taskKey)) {
                    log.info("收到回复停止下发命令");
                    // 如果为true 说明收到嵌入式的回复 删除内存中数据，并停止循环
                    SocketChannelMap.taskMapRemove(taskKey);
                    break;
                } else {
                	log.info("重复下发---"+i);
                    // 下发指令
                    channel.writeAndFlush(Unpooled.copiedBuffer(byteMsg));
                    Thread.sleep(2000);
                }
            }
        } catch (Exception e) {
        	log.error("下发报文：修改数字电位器数值线程失败："+e.getMessage());
        }
    }


}
